package com.heifeng.cloudshelf.mvp.main.presenter;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import androidx.core.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.heifeng.cloudshelf.R;
import com.heifeng.cloudshelf.base.BaseResponse;
import com.heifeng.cloudshelf.base.RxPresenter;
import com.heifeng.cloudshelf.constants.HTTPConstants;
import com.heifeng.cloudshelf.dao.AdvertisingBaen;
import com.heifeng.cloudshelf.dao.LoginBean;
import com.heifeng.cloudshelf.dao.MapBean;
import com.heifeng.cloudshelf.helper.MyObserver;
import com.heifeng.cloudshelf.helper.RxUtil;
import com.heifeng.cloudshelf.mvp.main.contract.MainActivityContract;
import com.heifeng.cloudshelf.network.NetClient;
import com.heifeng.cloudshelf.push.JpushUtils;
import com.heifeng.cloudshelf.utils.GlideImageLoader;
import com.heifeng.cloudshelf.utils.LocationUtils;
import com.heifeng.cloudshelf.utils.LoginErrorUtils;
import com.heifeng.cloudshelf.utils.ToastUitl;
import com.heifeng.cloudshelf.utils.UpdateUtils;
import com.heifeng.cloudshelf.utils.WifiUtils;
import com.heifeng.cloudshelf.widget.AppDialog;
import com.heifeng.cloudshelf.widget.CustomVideoPlayer;
import com.heifeng.cloudshelf.widget.JZMediaExo;
import com.orhanobut.hawk.Hawk;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import cn.jzvd.Jzvd;
import io.reactivex.disposables.Disposable;

/**
 * Created by admin on 2019/9/10.
 */

public class MainActivityPresenter extends RxPresenter<MainActivityContract.View> implements MainActivityContract.Presenter {
    private Animation animation;

    private int count = 0;
    private UpdateUtils updateUtils;
    private Handler _handler = new Handler();

    @Inject
    public MainActivityPresenter() {
    }

    @Override
    public void init() {
        animation = AnimationUtils.loadAnimation(mContext, R.anim.anim_small);

        initVideoPlayer(mView.getPlayer());
        mView.setLoginOutView(HTTPConstants.isLogined);
//        if (!HTTPConstants.isLogined) {
//            ShowLoginDialog();
//        }
//        checkUpdateApp();
    }

    @Override
    public void checkUpdateApp() {
        updateUtils = new UpdateUtils((isNewVersion, version) -> mView.ToastVersion(isNewVersion, version), mContext);
        updateUtils.startCheckVersion("b4f10dfef10d3c5659c90a221baf8e00");

    }


    @Override
    public void ShowLogoutDialog() {//退出登录dialog
        AppDialog.TwoButtonDialog(mContext, mContext.getResources().getString(R.string.text_logout_account), mContext.getResources().getString(R.string.text_logout_tips), "确认", "取消", new AppDialog.DoubleButtonOnClickListener() {
            @Override
            public void onLeftClick() {
            }

            @Override
            public void onRightClick() {
                toLoginOut();
            }
        }).showDialog();
    }

    //退出登录
    private void toLoginOut() {
        NetClient.getInstance().getNetApi().toLoginOut(NetClient.cliId, NetClient.token)
                .compose(RxUtil.<BaseResponse>rxSchedulers())
                .subscribe(new MyObserver<BaseResponse>(mContext) {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseResponse baseResponse) {
                        clearData();
                        //返回主页
                        ShowLoginDialog();
                    }
                });
    }

    @Override
    public void ShowTimeOverDialog(String message) {//到期提示dialog
        AppDialog.OneButtonDialog(mContext, mContext.getResources().getString(R.string.text_time_over_tips), message,
                mContext.getResources().getString(R.string.text_i_know), new AppDialog.OneButtonOnClickListener() {
                    @Override
                    public void onBtnClick() {
                        //ToastUitl.showLong("到期提示");
                        ShowLoginDialog();
                    }
                }).showDialog();
    }

    @Override
    public void ShowLocationFaildDialog() {//系统定位失败dialog
        AppDialog.OneButtonDialog(mContext, mContext.getResources().getString(R.string.text_location_failed), mContext.getResources().getString(R.string.text_location_failed_try_refresh),
                mContext.getResources().getString(R.string.text_refresh), new AppDialog.OneButtonOnClickListener() {
                    @Override
                    public void onBtnClick() {
                        gdLocation();
                    }
                }).showDialog();
    }

    @Override
    public void ShowLocationUnableDialog() {//未开启位置权限dialog
        AppDialog.OneButtonDialog(mContext, mContext.getResources().getString(R.string.text_location_unable), mContext.getResources().getString(R.string.text_open_location_first),
                mContext.getResources().getString(R.string.text_i_know), new AppDialog.OneButtonOnClickListener() {
                    @Override
                    public void onBtnClick() {
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }).showDialog();
    }

    @Override
    public void ShowLoginDialog() {//登录dialog
        Log.e("TAGS", "ShowLoginDialog");
        AppDialog.LoginDialog(mContext, mView.netConnect(), new AppDialog.LoginOnClickListener() {

            @Override
            public void onCodeClick(String phone) {//获取验证码
                getLoginCode(phone);
                // ToastUitl.showLong("请求验证码完成");
            }

            @Override
            public void onLoginClick(AppDialog dialog, String phone, String code) {
                toLogin(dialog, phone, code);
            }
        }).showDialog();

    }

    //用户登录
    private void toLogin(AppDialog dialog, String phone, String code) {
        if (TextUtils.isEmpty(HTTPConstants.macAddress)) {
            HTTPConstants.macAddress = WifiUtils.getMacAddress(mContext).replaceAll(":", "");
            JpushUtils.setAlias(mContext, HTTPConstants.macAddress);
        }
        Log.e("TAGS", "macAddress:" + HTTPConstants.macAddress);
        NetClient.getInstance().getNetApi().toLogin(phone, code, HTTPConstants.macAddress)
                .compose(RxUtil.<BaseResponse<LoginBean>>rxSchedulers())
                .subscribe(new MyObserver<BaseResponse<LoginBean>>(mContext) {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse<LoginBean> baseResponse) {
                        if (0 == baseResponse.getCode()) {
                            LoginBean login = baseResponse.getresult();
                            NetClient.token = login.getToken();
                            NetClient.cliId = login.getCliId();
                            HTTPConstants.userId = phone;
                            Hawk.put(HTTPConstants.USER_ID_KEY, phone);
                            Hawk.put(HTTPConstants.CLIID_KEY, login.getCliId());
                            Hawk.put(HTTPConstants.TOKEN_KEY, login.getToken());
                            Log.e("Login", "token:" + NetClient.token);
                            if (null != dialog) {
                                dialog.dismiss();
                                Log.e("Login", "close dialog");
                            }
                            mView.setLoginOutView(true);
                            if (null == Hawk.get(HTTPConstants.PERMISSION_KEY)) {
                                ShowAllowLocationDialog();
                            } else {
                                boolean isPermission = Hawk.get(HTTPConstants.PERMISSION_KEY);
                                if (!isPermission) {
                                    ShowAllowLocationDialog();
                                }
                            }

                        } else {
                            if (600001 == baseResponse.getCode()) {
                                clearData();
                                ShowTimeOverDialog(baseResponse.getmsg());
                            }
//                            ShowLoginDialog();
                            ToastUitl.showLong(baseResponse.getmsg());
                        }
                    }
                });
    }

    private void clearData() {
        mView.setLoginOutView(false);
        NetClient.cliId = "";
        NetClient.token = "";
        HTTPConstants.userId = "";
        HTTPConstants.isLogined = false;
        Hawk.delete(HTTPConstants.USER_ID_KEY);
        Hawk.delete(HTTPConstants.TOKEN_KEY);
        Hawk.delete(HTTPConstants.CLIID_KEY);
    }

    //获取手机验证码
    private void getLoginCode(String phone) {
        NetClient.getInstance().getNetApi()
                .getLoginCode(phone).compose(RxUtil.rxSchedulers())
                .subscribe(new MyObserver<BaseResponse>(mContext) {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseResponse baseResponse) {
                        if (null != mView) {
                            mView.toastCodeText(baseResponse);
                        }
//                        _handler.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (0 == baseResponse.getCode()) {
//                                    ToastUitl.showLong(baseResponse.getmsg());
//                                    AppDialog.countTime(120);
//                                } else {
//                                    ToastUitl.showLong(baseResponse.getmsg());
//                                    if (600001 == baseResponse.getCode()) {
////                                        ShowTimeOverDialog(baseResponse.getmsg());
////                                    }
//                                }
//                            }
//                        });
                    }
                });
    }

    @Override
    public void ShowAllowLocationDialog() {//允许访问位置信息dialog
        AppDialog.AllowLocationDialog(mContext, new AppDialog.DoubleButtonOnEnquireClickListener() {
            @Override
            public void onLeftClick(boolean isEnquire) {
                //不允许
                Log.e("AllowLocation", "isEnquire:" + isEnquire);
                Hawk.put(HTTPConstants.PERMISSION_KEY, false);
                if (isEnquire) {
                    ShowLocationUnableDialog();
                } else {
                    //返回主页
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            }

            @Override
            public void onRightClick(boolean isEnquire) {
                gdLocation();
            }
        }).showDialog();
    }

    @Override
    public void UpdateTipsDialog() {//更新提示
        AppDialog.OneButtonDialog(mContext, mContext.getResources().getString(R.string.text_version_update), mContext.getResources().getString(R.string.app_name) + mContext.getResources().getString(R.string.text_version_update_tips),
                mContext.getResources().getString(R.string.text_update_now), new AppDialog.OneButtonOnClickListener() {
                    @Override
                    public void onBtnClick() {
                        UpdateProgressDialog();
                    }
                }).showDialog();
    }

    @Override
    public void UpdateFinishedDialog() {//更新完成
        AppDialog.OneButtonDialog(mContext, mContext.getResources().getString(R.string.text_update_finished), mContext.getResources().getString(R.string.app_name) + mContext.getResources().getString(R.string.text_update_finished_tips),
                mContext.getResources().getString(R.string.text_use_now), new AppDialog.OneButtonOnClickListener() {
                    @Override
                    public void onBtnClick() {
                        //安装pak
                        installApk(mContext.getExternalCacheDir().getAbsolutePath() + "/" + mContext.getResources().getString(R.string.app_name) + ".apk");
                    }
                }).showDialog();
    }

    public void installApk(String downloadApk) {
        if (!TextUtils.isEmpty(downloadApk)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            File file = new File(downloadApk);
            Log.e("TAGS", "安装路径==" + downloadApk);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri apkUri = FileProvider.getUriForFile(mContext, "com.heifeng.cloudshelf.fileprovider", file);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri uri = Uri.fromFile(file);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
            }
            mContext.startActivity(intent);
        }
    }

    @Override
    public void UpdateProgressDialog() {//更新进度
        AppDialog.ProgressDialog(mContext,mView.getThisActivity(), mContext.getResources().getString(R.string.text_version_update)
                , mContext.getResources().getString(R.string.text_version_update_tips),
                isError -> {
                    if (isError) {
                        //下载完成
                        UpdateFinishedDialog();
                    } else {
                        //下载失败

                    }
                }).showDialog();
    }

    @Override
    public void ImageViewClickChange(ImageView imageView, int type) {//图片点击变大，再还原
        imageView.startAnimation(animation);
//        animation.setAnimationListener(new Animation.AnimationListener() {
//            @Override
//            public void onAnimationStart(Animation animation) {
//
//            }
//
//            @Override
//            public void onAnimationEnd(Animation animation) {
//                mView.animationEnd(type);
//            }
//
//            @Override
//            public void onAnimationRepeat(Animation animation) {
//
//            }
//        });
    }

    public void initBanner(Banner banner) {//初始化banner
        List imageList = new ArrayList();
        imageList.add(R.mipmap.banner_2);
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(imageList);
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(4000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);

        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {//banner点击事件
                ToastUitl.showLong("banner点击了--" + position);
            }
        });

        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    public void initVideoPlayer(CustomVideoPlayer videoPlayer) {
        videoPlayer.setAllowPlay(true);//设置视频是否允许播放
        videoPlayer.setUp("https://interface.sina.cn/wap_api/video_location.d.html?cid=37767&table_id=36885&did=hytcern2812545&vt=4&creator_id=1006,9796,9797&vid=30163047603&video_id=301630476&r=video.sina.cn%2Fsports%2F2019-08-22%2Fdetail-ihytcern2812545.d.html&wm=3049_00051035352176&time=1568552855417&rd=0.055459183248854016"
                , "", Jzvd.SCREEN_NORMAL, JZMediaExo.class);
        //设置视频预览图,预览图链接为空，则是黑色背景
        Glide.with(mContext).load(R.mipmap.ic_video_default).into(videoPlayer.thumbImageView);

    }

    @Override
    public void gdLocation() {
        LocationUtils.synchronizedGetRequests(HTTPConstants.MAPURL, new LocationUtils.OnMessageCallBack() {
            @Override
            public void onMessage(String message) {
                Log.e("TAGS", "message:" + message);
                MapBean mapBean = new Gson().fromJson(message, MapBean.class);
                if (!TextUtils.isEmpty(mapBean.getCity())) {
                    Hawk.put(HTTPConstants.CITY_KEY, mapBean.getCity());
                    Hawk.put(HTTPConstants.PERMISSION_KEY, true);
                    HTTPConstants.city = mapBean.getCity();
                } else {
                    Hawk.put(HTTPConstants.PERMISSION_KEY, false);
                    mView.locationError();
                }
            }

            @Override
            public void onError() {
                Hawk.put(HTTPConstants.PERMISSION_KEY, false);
                mView.locationError();
            }
        });
    }

    @Override
    public void getAdvertising() {
        NetClient.getInstance().getNetApi().toGetAdvertising()
                .compose(RxUtil.<BaseResponse<AdvertisingBaen>>rxSchedulers())
                .subscribe(new MyObserver<BaseResponse<AdvertisingBaen>>(mContext) {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse<AdvertisingBaen> baseResponse) {
                        if (0 == baseResponse.getCode()) {
                            Log.e("Advertising", "Advertising image:" + baseResponse.getresult().getPic());
                            if (null != mView) {
                                mView.setImageAndVideoData(baseResponse.getresult().getPic(), baseResponse.getresult().getVideoUrl(), baseResponse.getresult().getVideoPic());
                            }
                        } else {
                            LoginErrorUtils.loginOut(mContext, baseResponse.getCode(), baseResponse.getmsg());
                        }
                    }
                });
    }
}
